<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CustomerAction
 *
 * @author 志鹏
 */
class CustomerAction extends CommonAction {
    
    public $relation = true;
    
    protected function _filter(&$map) {
        $map["status|user_id"] = array('1', $this->user["id"],'_multi'=>true);
    }
    
    public function index() {
        
        $map = $this->_search();
        $this->_filter($map);
        parent::index("Customer", true);
    }
    
    public function insert() {
        $_POST["dateline"] = CTS;
//        $_POST["status"] = 1;
        $_POST["user_id"] = $_SESSION["user"]["id"];
        $id = parent::insert(true);
        if($_POST["insert_linkman"] and $id) {
            $data = array(
                "customer_id" => $id,
                "contact" => $_POST["contact"],
                "phone1"  => $_POST["phone"],
                "dateline"=> $_POST["dateline"],
                "email"   => $_POST["email"],
                "dateline"=> CTS
            );
            $customerLinkman = D("CustomerLinkman");
            $customerLinkman->add($data);
        }
        
        if($_POST["goto"]) {
            $this->redirect($_POST["goto"].sprintf("/customer_id/%d/customer_name/%s", $id, $_POST["name"]));
        } else {
            $this->success(L("operate_success"));
        }
    }
    
    public function viewDetail() {
        $id = abs(intval($_GET["id"]));
        $theCustomer = D("Customer")->relation(true)->find($id);
        $this->assign("theCustomer", $theCustomer);
        $this->display();
    }
    
    
    /**
     * Ajax获取客户列表
     */
    public function ajax_getCustomers() {
        $name = trim(strip_tags($_GET["term"]));
        $customer = D("Customer");
        $map["status|user_id"] = array('1', $this->user["id"],'_multi'=>true);
        $map["name"] = array("LIKE", "%".$name."%");
        $data = $customer->where($map)->select();
//        echo $customer->getLastSql();
        if(!$data) {
            $this->ajaxReturn(array());
        }
        
        foreach($data as $k=>$v) {
            $_data[] = array(
                "id" => $v["id"],
                "label" => $v["name"],
                "value" => $v["name"]
            );
        }
        return $this->ajaxReturn($_data);
    }
    
    
}
